﻿using Aspose.Words;
using Aspose.Words.Drawing;
using Aspose.Words.Fields;
using Aspose.Words.Reporting;
using MyCompanyName.AbpZeroTemplate.Prm.Project.Dto;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace MyCompanyName.AbpZeroTemplate.Prm.Project.ProjectTaskExport
{
    public class WordHelper
    {



        private static void Crack()//使用前调用一次即可
        {
            string[] stModule = new string[8]
            {
                "\u000E\u2008\u200A\u2001",
                "\u000F\u2008\u200A\u2001",
                "\u0002\u200A\u200A\u2001",
                "\u000F",
                "\u0006",
                "\u000E",
                "\u0003",
                "\u0002"
            };
            Assembly assembly = Assembly.GetAssembly(typeof(Aspose.Words.License));

            Type typeLic = null, typeIsTrial = null, typeHelper = null;
            foreach (Type type in assembly.GetTypes())
            {
                if ((typeLic == null) && (type.Name == stModule[0]))
                {
                    typeLic = type;
                }
                else if ((typeIsTrial == null) && (type.Name == stModule[1]))
                {
                    typeIsTrial = type;
                }
                else if ((typeHelper == null) && (type.Name == stModule[2]))
                {
                    typeHelper = type;
                }
            }
            if (typeLic == null || typeIsTrial == null || typeHelper == null)
            {
                throw new Exception();
            }
            object lic = Activator.CreateInstance(typeLic);
            int findCount = 0;

            foreach (System.Reflection.FieldInfo field in typeLic.GetFields(BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance))
            {
                if (field.FieldType == typeLic && field.Name == stModule[3])
                {
                    field.SetValue(null, lic);
                    ++findCount;
                }
                else if (field.FieldType == typeof(DateTime) && field.Name == stModule[4])
                {
                    field.SetValue(lic, DateTime.MaxValue);
                    ++findCount;
                }
                else if (field.FieldType == typeIsTrial && field.Name == stModule[5])
                {
                    field.SetValue(lic, 1);
                    ++findCount;
                }

            }
            foreach (System.Reflection.FieldInfo field in typeHelper.GetFields(BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance))
            {
                if (field.FieldType == typeof(bool) && field.Name == stModule[6])
                {
                    field.SetValue(null, false);
                    ++findCount;
                }
                if (field.FieldType == typeof(int) && field.Name == stModule[7])
                {
                    field.SetValue(null, 128);
                    ++findCount;
                }
            }
            if (findCount < 5)
            {
                throw new NotSupportedException("无效的版本");
            }
        }

        public string ToText(string filePath = "")
        {
            if (string.IsNullOrEmpty(filePath))
            {
                throw new Exception("导入文件路径为nul");
            }
            Crack();
            // Open the document we want to convert.
            Aspose.Words.Document doc = new Aspose.Words.Document(filePath);

            // Create an object that inherits from the DocumentVisitor class.
            MyDocToTxtWriter myConverter = new MyDocToTxtWriter();

            // This is the well known Visitor pattern. Get the model to accept a visitor.
            // The model will iterate through itself by calling the corresponding methods
            // on the visitor object (this is called visiting).
            // 
            // Note that every node in the object model has the Accept method so the visiting
            // can be executed not only for the whole document, but for any node in the document.
            doc.Accept(myConverter);

            // Once the visiting is complete, we can retrieve the result of the operation,
            // that in this example, has accumulated in the visitor.
            string res = myConverter.GetText();
            return res;
        }

        /// <summary>
        /// Simple implementation of saving a document in the plain text format. Implemented as a Visitor.
        /// </summary>
        public class MyDocToTxtWriter : DocumentVisitor
        {
            public MyDocToTxtWriter()
            {
                mIsSkipText = false;
                mBuilder = new StringBuilder();
            }

            /// <summary>
            /// Gets the plain text of the document that was accumulated by the visitor.
            /// </summary>
            public string GetText()
            {
                return mBuilder.ToString();
            }

            /// <summary>
            /// Called when a Run node is encountered in the document.
            /// </summary>
            public override VisitorAction VisitRun(Run run)
            {
                AppendText(run.Text);

                // Let the visitor continue visiting other nodes.
                return VisitorAction.Continue;
            }

            /// <summary>
            /// Called when a FieldStart node is encountered in the document.
            /// </summary>
            public override VisitorAction VisitFieldStart(FieldStart fieldStart)
            {
                // In Microsoft Word, a field code (such as "MERGEFIELD FieldName") follows
                // after a field start character. We want to skip field codes and output field 
                // result only, therefore we use a flag to suspend the output while inside a field code.
                //
                // Note this is a very simplistic implementation and will not work very well
                // if you have nested fields in a document. 
                mIsSkipText = true;

                return VisitorAction.Continue;
            }

            /// <summary>
            /// Called when a FieldSeparator node is encountered in the document.
            /// </summary>
            public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
            {
                // Once reached a field separator node, we enable the output because we are
                // now entering the field result nodes.
                mIsSkipText = false;

                return VisitorAction.Continue;
            }

            /// <summary>
            /// Called when a FieldEnd node is encountered in the document.
            /// </summary>
            public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
            {
                // Make sure we enable the output when reached a field end because some fields
                // do not have field separator and do not have field result.
                mIsSkipText = false;

                return VisitorAction.Continue;
            }

            /// <summary>
            /// Called when visiting of a Paragraph node is ended in the document.
            /// </summary>
            public override VisitorAction VisitParagraphEnd(Paragraph paragraph)
            {
                // When outputting to plain text we output Cr+Lf characters.
                AppendText(ControlChar.CrLf);

                return VisitorAction.Continue;
            }

            public override VisitorAction VisitBodyStart(Body body)
            {
                // We can detect beginning and end of all composite nodes such as Section, Body, 
                // Table, Paragraph etc and provide custom handling for them.
                mBuilder.Append("*** Body Started ***\r\n");

                return VisitorAction.Continue;
            }

            public override VisitorAction VisitBodyEnd(Body body)
            {
                mBuilder.Append("*** Body Ended ***\r\n");
                return VisitorAction.Continue;
            }

            /// <summary>
            /// Called when a HeaderFooter node is encountered in the document.
            /// </summary>
            public override VisitorAction VisitHeaderFooterStart(HeaderFooter headerFooter)
            {
                // Returning this value from a visitor method causes visiting of this
                // node to stop and move on to visiting the next sibling node.
                // The net effect in this example is that the text of headers and footers
                // is not included in the resulting output.
                return VisitorAction.SkipThisNode;
            }


            /// <summary>
            /// Adds text to the current output. Honours the enabled/disabled output flag.
            /// </summary>
            private void AppendText(string text)
            {
                if (!mIsSkipText)
                    mBuilder.Append(text);
            }

            private readonly StringBuilder mBuilder;
            private bool mIsSkipText;
        }




        //  http://www.cnblogs.com/birchlee/archive/2013/05/23/3094632.html

        public string Report(ProjectExportInfo project, SaveFormat format)
        {
            string tempPath = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + @"App_Data\report_tpl\Weekly.docx";
            Crack();
            var doc = new Aspose.Words.Document(tempPath);
            doc.MailMerge.FieldMergingCallback = new HandleMergeFieldInsertDocument();


            // 全局的 研发中心 变量
            String[] fieldNames = new String[] { "weeklyTitle", "ChemicalName", "ProjectCode", "CAS", "chemdraw", 
                "CustomerCode", "Status", "Duration", "ProjectLeader", "Deliverables", "Timelines",
                "Gantt", "SyntheticScheme" };
            Object[] fieldValues = new Object[] { project.ProjectCode, project.ChemicalName, project.ProjectCode, project.CAS, project.Img,
                project.CustomerCode, project.Status, project.Duration, project.ProjectLeader, project.Deliverables, project.Timelines, 
                project.Gantt, project.SyntheticScheme };
            doc.MailMerge.Execute(fieldNames, fieldValues);


            //DataTable table = new DataTable("tasks");
            //table.Columns.Add("taskTitle");
            //table.Columns.Add("binaries");
            //foreach (var item in answers)
            //{
            //    var w1 = table.NewRow();
            //    w1["taskTitle"] =item;
            //    w1["binaries"] = item;
            //    table.Rows.Add(w1);
            //}
            //doc.MailMerge.ExecuteWithRegions(table);

            DataTable tags = new DataTable("tags");
            tags.Columns.Add(new DataColumn("Id", typeof(int)));
            tags.Columns.Add("tName");

            DataTable routes = new DataTable("routes");
            routes.Columns.Add(new DataColumn("tagId", typeof(int)));//外键字段，关联主表Id
            routes.Columns.Add(new DataColumn("Id", typeof(int)));
            routes.Columns.Add("rName");


            DataTable steps = new DataTable("steps");
            steps.Columns.Add(new DataColumn("routeId", typeof(int)));//外键字段，关联主表Id
            steps.Columns.Add(new DataColumn("Id", typeof(int)));
            steps.Columns.Add("sName");


            DataTable aspects = new DataTable("aspects");
            aspects.Columns.Add(new DataColumn("stepId", typeof(int)));//外键字段，关联主表Id
            aspects.Columns.Add(new DataColumn("Id", typeof(int)));
            aspects.Columns.Add("aName");

            DataTable qas = new DataTable("qas");
            qas.Columns.Add(new DataColumn("aspectId", typeof(int)));//外键字段，关联主表Id
            qas.Columns.Add(new DataColumn("Id", typeof(int)));
            qas.Columns.Add("question");
            qas.Columns.Add("description");
            qas.Columns.Add("answerResult");



            foreach (var tag in project.Tags)
            {
                var t1 = tags.NewRow();
                t1["Id"] = tag.Id;
                t1["tName"] = tag.Name;
                tags.Rows.Add(t1);
                foreach (var route in tag.Routes)
                {
                    var r1 = routes.NewRow();
                    r1["Id"] = route.Id;
                    r1["tagId"] = tag.Id;
                    r1["rName"] = route.Name;
                    routes.Rows.Add(r1);

                    foreach (var step in route.Steps)
                    {
                        var s1 = steps.NewRow();
                        s1["routeId"] = route.Id;
                        s1["Id"] = step.Id;
                        s1["sName"] = step.Name;
                        steps.Rows.Add(s1);

                        foreach (var aspect in step.Aspects)
                        {
                            var a1 = aspects.NewRow();
                            a1["stepId"] = step.Id;
                            a1["Id"] = aspect.Id;
                            a1["aName"] = aspect.Name;
                            aspects.Rows.Add(a1);

                            foreach (var qa in aspect.Qas)
                            {
                                var q1 = qas.NewRow();
                                q1["aspectId"] = aspect.Id;
                                q1["Id"] = qa.Id;
                                q1["question"] = qa.Question;
                                q1["answerResult"] = qa.AnswerResult.LastOrDefault();
                                q1["description"] = qa.Description.LastOrDefault();
                                qas.Rows.Add(q1);
                            }
                        }
                    }
                }
            }

            //=========================================================== 组装表
            DataSet dataSet = new DataSet();
            dataSet.Tables.Add(tags);
            dataSet.Tables.Add(routes);
            dataSet.Relations.Add(new DataRelation("tag2route", tags.Columns["Id"], routes.Columns["tagId"]));

            dataSet.Tables.Add(steps);
            dataSet.Relations.Add(new DataRelation("route2step", routes.Columns["Id"], steps.Columns["routeId"]));

            dataSet.Tables.Add(aspects);
            dataSet.Relations.Add(new DataRelation("step2aspects", steps.Columns["Id"], aspects.Columns["stepId"]));

            dataSet.Tables.Add(qas);
            dataSet.Relations.Add(new DataRelation("aspects2qa", aspects.Columns["Id"], qas.Columns["aspectId"]));

            //合并模版，相当于页面的渲染
            doc.MailMerge.ExecuteWithRegions(dataSet);

            string putPath = "";
            //if (format == SaveFormat.WordML)
            //{
            putPath = @"Logs\weekly_result.doc";
            //}
            //else
            //{
            //    putPath = @"Logs\weekly_result.pdf";
            //}
            doc.Save(System.Web.HttpContext.Current.Request.PhysicalApplicationPath + putPath, format);
            return putPath;
        }


        public System.IO.Stream InquiryXml(GetInquiryOutPut inquiry, string fileRootPath)
        {
            string tempPath = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + fileRootPath;
            Crack();

            var Year = DateTime.Now.Year;
            var Month = DateTime.Now.Month;
            var Day = DateTime.Now.Day;

            var doc = new Aspose.Words.Document(tempPath);
            doc.MailMerge.FieldMergingCallback = new HandleMergeFieldInsertDocument();


            // 全局的 研发中心 变量
            String[] fieldNames = new String[] { "ProjectNo", "CreateOn", "ProjectName", "ProjectType", "InquiryNo", 
                "CustomerNo", "SubName", "SubCas", "MF", "MW", "IMG",
                "AdminName", "CustomerName","ProductName"
                ,"spec","synth","Phase","Indication","SafeOrNot","NeedCurNum","NeedMaxNum"
                ,"Purpose","TargetDate","Files","ProductName","WeekReport","Year","Month","Day","CreateBy"
            };
            Object[] fieldValues = new Object[] { inquiry.ProjectNo,inquiry.CreateOn.ToString("yyyy-MM-dd"),inquiry.ProjectName,inquiry.ProjectType,inquiry.InquiryNo,
                inquiry.CustomerNo,inquiry.SubName,inquiry.SubCas,inquiry.MF,inquiry.MW,inquiry.ImgBt,
                inquiry.AdminName,inquiry.CustomerName,inquiry.ProductName,
                inquiry.spec,inquiry.synth,inquiry.Phase,inquiry.Indication,inquiry.SafeOrNot,inquiry.NeedCurNum,inquiry.NeedMaxNum,
                inquiry.Purpose,inquiry.TargetDate.ToString("yyyy-MM-dd"),inquiry.Files,inquiry.ProductName,inquiry.WeekReport.ToString(),
                Year.ToString(),Month.ToString(),Day.ToString(),inquiry.CreateBy
            };
            doc.MailMerge.Execute(fieldNames, fieldValues);


            //保存合并后的文档
            string outputPath = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + @"Logs\inquiryXML.doc";
            doc.Save(outputPath);


            System.IO.MemoryStream stream = new System.IO.MemoryStream();
            doc.Save(stream, SaveFormat.Doc);
            stream.Position = 0;
            return stream;
        }


        private class HandleMergeFieldInsertDocument : Aspose.Words.MailMerging.IFieldMergingCallback
        {


            //文本处理在这里
            public void FieldMerging(Aspose.Words.MailMerging.FieldMergingArgs e)
            {
                switch (e.DocumentFieldName)
                {
                    case "answerResult":
                        string root = System.Configuration.ConfigurationManager.AppSettings["fileServer"];
                        if (e.FieldValue != null && e.FieldValue.ToString().Length > 2)
                        {

                            DocumentBuilder builder = new DocumentBuilder(e.Document);
                            builder.MoveToMergeField(e.DocumentFieldName);
                            var file = Abp.GridFS.GridFSHelper.Get(Guid.Parse(e.FieldValue.ToString()));
                            builder.InsertHtml(string.Format("<a href='{0}'>{1}</a>", string.Format("{0}/api/services/app/document/GetFile?path={1}", root, file.Id), file.FileName));
                            //MemoryStream ms = new MemoryStream(file.FileBytes);
                            //string fileExtension = file.ExtensionName.ToLower();
                            ////if (file == null || fileExtension.IndexOf("doc") == -1)
                            //{
                            //    builder.InsertHtml(file.FileName);

                            //    string imgPath = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + @"App_Data\fileIcon\unknow.png";

                            //    //if (fileExtension.IndexOf("pdf") > -1)
                            //    //{
                            //    //    imgPath = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + @"App_Data\fileIcon\pdf.png";
                            //    //    builder.InsertOleObject(ms, "acroexch.document", true, System.Drawing.Image.FromFile(imgPath));
                            //    //}
                            //    //else if (fileExtension.IndexOf("ppt") > -1)
                            //    //{
                            //    //    imgPath = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + @"App_Data\fileIcon\ppt.png";
                            //    //    builder.InsertOleObject(ms, "powerpoint.show.8", true, System.Drawing.Image.FromFile(imgPath));
                            //    //}
                            //    //else if (fileExtension.IndexOf("xls") > -1)
                            //    //{
                            //    //    imgPath = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + @"App_Data\fileIcon\xls.png";
                            //    //    builder.InsertOleObject(ms, "excel.sheet.8", true, System.Drawing.Image.FromFile(imgPath));
                            //    //}
                            //    //else if (fileExtension.IndexOf("doc") > -1)
                            //    //{
                            //    //    imgPath = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + @"App_Data\fileIcon\word.png";
                            //    //    builder.InsertOleObject(ms, "Word.document", true, System.Drawing.Image.FromFile(imgPath));
                            //    //}
                            //    //else if (fileExtension.IndexOf("rar") > -1)
                            //    //{
                            //    //    imgPath = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + @"App_Data\fileIcon\rar.png";
                            //    //    builder.InsertOleObject(ms, "", true, System.Drawing.Image.FromFile(imgPath));
                            //    //}
                            //    //else
                            //    //{
                            //    //    builder.InsertOleObject(ms, "", true, System.Drawing.Image.FromFile(imgPath));
                            //    //}
                            //    if (fileExtension.IndexOf("pdf") > -1)
                            //    {
                            //        imgPath = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + @"App_Data\fileIcon\pdf.png";
                            //    }
                            //    else if (fileExtension.IndexOf("ppt") > -1)
                            //    {
                            //        imgPath = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + @"App_Data\fileIcon\ppt.png";
                            //    }
                            //    else if (fileExtension.IndexOf("xls") > -1)
                            //    {
                            //        imgPath = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + @"App_Data\fileIcon\xls.png";
                            //    }
                            //    else if (fileExtension.IndexOf("doc") > -1)
                            //    {
                            //        imgPath = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + @"App_Data\fileIcon\word.png";
                            //    }
                            //    else if (fileExtension.IndexOf("rar") > -1)
                            //    {
                            //        imgPath = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + @"App_Data\fileIcon\rar.png";
                            //    }
                            //    builder.InsertOleObject(ms, "acroexch.document", true, System.Drawing.Image.FromFile(imgPath));
                            //    builder.InsertHtml("test");
                            break;
                            //}


                            ////var bytes = System.IO.File.ReadAllBytes(@"C:\Users\chaoshuai.lu\Desktop\wordTest\ConsoleApplication1\The synthesis of C-509.docx");
                            ////System.IO.MemoryStream stream = new System.IO.MemoryStream(bytes);
                            //Aspose.Words.Document subDoc = new Aspose.Words.Document(ms);

                            //// Insert the document.
                            //InsertDocument(builder.CurrentParagraph, subDoc);


                            //// The paragraph that contained the merge field might be empty now and you probably want to delete it.
                            //if (!builder.CurrentParagraph.HasChildNodes)
                            //    builder.CurrentParagraph.Remove();

                            //// Indicate to the mail merge engine that we have inserted what we wanted.
                            //e.Text = null;
                        }
                        break;
                    case "html":
                        if (e.FieldValue != null && e.FieldValue.ToString().Length > 3)
                        {
                            DocumentBuilder builder = new DocumentBuilder(e.Document);
                            builder.MoveToMergeField(e.DocumentFieldName);
                            builder.InsertHtml(e.FieldValue.ToString());
                        }
                        break;
                    case "Files":
                        if (e.FieldValue != null && e.FieldValue.ToString().Length > 3)
                        {
                            //DocumentBuilder builder = new DocumentBuilder(e.Document);

                            //builder.MoveToMergeField(e.DocumentFieldName);
                            ////builder.ins(e.FieldValue.ToString());



                            DocumentBuilder builder = new DocumentBuilder(e.Document);
                            builder.MoveToMergeField(e.DocumentFieldName);

                            List<FileJson> files = (List<FileJson>)Newtonsoft.Json.JsonConvert.DeserializeObject<List<FileJson>>(e.FieldValue.ToString());
                            foreach (FileJson fItem in files)
                            {
                                var file = Abp.GridFS.GridFSHelper.Get(fItem.FullPath);
                                if (file == null)
                                    continue;
                                MemoryStream ms = new MemoryStream(file.FileBytes);
                                string fileExtension = file.ExtensionName.ToLower();

                                builder.InsertHtml(file.FileName);

                                string imgPath = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + @"App_Data\fileIcon\unknow.png";

                                if (fileExtension.IndexOf("pdf") > -1)
                                {
                                    imgPath = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + @"App_Data\fileIcon\pdf.png";
                                    builder.InsertOleObject(ms, "acroexch.document", true, System.Drawing.Image.FromFile(imgPath));
                                }
                                else if (fileExtension.IndexOf("ppt") > -1)
                                {
                                    imgPath = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + @"App_Data\fileIcon\ppt.png";
                                    builder.InsertOleObject(ms, "powerpoint.show.8", true, System.Drawing.Image.FromFile(imgPath));
                                }
                                else if (fileExtension.IndexOf("xls") > -1)
                                {
                                    imgPath = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + @"App_Data\fileIcon\xls.png";
                                    builder.InsertOleObject(ms, "excel.sheet.8", true, System.Drawing.Image.FromFile(imgPath));
                                }
                                else if (fileExtension.IndexOf("rar") > -1)
                                {
                                    imgPath = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + @"App_Data\fileIcon\rar.png";
                                    builder.InsertOleObject(ms, "", true, System.Drawing.Image.FromFile(imgPath));
                                }
                                else if (fileExtension.IndexOf("doc") > -1)
                                {
                                    imgPath = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + @"App_Data\fileIcon\word.png";
                                    builder.InsertOleObject(ms, "", true, System.Drawing.Image.FromFile(imgPath));
                                }
                                else
                                {
                                    builder.InsertOleObject(ms, "", true, System.Drawing.Image.FromFile(imgPath));
                                }


                            }
                        }
                        break;
                    default:
                        break;
                }
            }

            //图片处理在这里
            public void ImageFieldMerging(Aspose.Words.MailMerging.ImageFieldMergingArgs args)
            {
                if (args.DocumentFieldName.Equals("chemdraw"))
                {
                    if (args.FieldValue == null || args.FieldValue.ToString().Length < 10)
                    {
                        return;
                    }

                    // 使用DocumentBuilder处理图片的大小
                    DocumentBuilder builder = new DocumentBuilder(args.Document);
                    builder.MoveToMergeField(args.FieldName);
                    byte[] arr = args.FieldValue as byte[];
                    //var arr = System.IO.File.ReadAllBytes(@"D:\ico\Chemical.jpg");

                    Aspose.Words.Drawing.Shape shape = builder.InsertImage(arr);
                    // 设置x,y坐标和高宽.
                    shape.Left = 0;
                    shape.Top = 0;
                    shape.Width = 60;
                    shape.Height = 80;
                }
            }
        }




        /// <summary>
        /// Inserts content of the external document after the specified node.
        /// Section breaks and section formatting of the inserted document are ignored.
        /// </summary>
        /// <param name="insertAfterNode">Node in the destination document after which the content
        /// should be inserted. This node should be a block level node (paragraph or table).</param>
        /// <param name="srcDoc">The document to insert.</param>
        private static void InsertDocument(Node insertAfterNode, Aspose.Words.Document srcDoc)
        {
            // Make sure that the node is either a paragraph or table.
            if ((!insertAfterNode.NodeType.Equals(NodeType.Paragraph)) &
              (!insertAfterNode.NodeType.Equals(NodeType.Table)))
                throw new ArgumentException("The destination node should be either a paragraph or table.");

            // We will be inserting into the parent of the destination paragraph.
            CompositeNode dstStory = insertAfterNode.ParentNode;

            // This object will be translating styles and lists during the import.
            NodeImporter importer = new NodeImporter(srcDoc, insertAfterNode.Document, ImportFormatMode.KeepSourceFormatting);

            // Loop through all sections in the source document.
            foreach (Section srcSection in srcDoc.Sections)
            {
                // Loop through all block level nodes (paragraphs and tables) in the body of the section.
                foreach (Node srcNode in srcSection.Body)
                {
                    // Let's skip the node if it is a last empty paragraph in a section.
                    if (srcNode.NodeType.Equals(NodeType.Paragraph))
                    {
                        Paragraph para = (Paragraph)srcNode;
                        if (para.IsEndOfSection && !para.HasChildNodes)
                            continue;
                    }

                    // This creates a clone of the node, suitable for insertion into the destination document.
                    Node newNode = importer.ImportNode(srcNode, true);

                    // Insert new node after the reference node.
                    dstStory.InsertAfter(newNode, insertAfterNode);
                    insertAfterNode = newNode;
                }
            }
        }





        /// <summary>
        /// Inserts content of the external document after the specified node.
        /// </summary>
        /// <param name="insertAfterNode">Node in the destination document after which the content
        /// should be inserted. This node should be a block level node (paragraph or table).</param>
        /// <param name="srcDoc">The document to insert.</param>
        private static void InsertDocumentWithSectionFormatting(Node insertAfterNode, Aspose.Words.Document srcDoc)
        {
            // Make sure that the node is either a pargraph or table.
            if ((!insertAfterNode.NodeType.Equals(NodeType.Paragraph)) &
                (!insertAfterNode.NodeType.Equals(NodeType.Table)))
                throw new ArgumentException("The destination node should be either a paragraph or table.");

            // Document to insert srcDoc into.
            Aspose.Words.Document dstDoc = (Aspose.Words.Document)insertAfterNode.Document;
            // To retain section formatting, split the current section into two at the marker node and then import the content from srcDoc as whole sections.
            // The section of the node which the insert marker node belongs to
            Section currentSection = (Section)insertAfterNode.GetAncestor(NodeType.Section);

            // Don't clone the content inside the section, we just want the properties of the section retained.
            Section cloneSection = (Section)currentSection.Clone(false);

            // However make sure the clone section has a body, but no empty first paragraph.
            cloneSection.EnsureMinimum();
            cloneSection.Body.FirstParagraph.Remove();

            // Insert the cloned section into the document after the original section.
            insertAfterNode.Document.InsertAfter(cloneSection, currentSection);

            // Append all nodes after the marker node to the new section. This will split the content at the section level at
            // the marker so the sections from the other document can be inserted directly.
            Node currentNode = insertAfterNode.NextSibling;
            while (currentNode != null)
            {
                Node nextNode = currentNode.NextSibling;
                cloneSection.Body.AppendChild(currentNode);
                currentNode = nextNode;
            }

            // This object will be translating styles and lists during the import.
            NodeImporter importer = new NodeImporter(srcDoc, dstDoc, ImportFormatMode.UseDestinationStyles);

            // Loop through all sections in the source document.
            foreach (Section srcSection in srcDoc.Sections)
            {
                Node newNode = importer.ImportNode(srcSection, true);

                // Append each section to the destination document. Start by inserting it after the split section.
                dstDoc.InsertAfter(newNode, currentSection);
                currentSection = (Section)newNode;
            }
        }




        public class FileJson
        {
            public Guid Id { get; set; }
            public string Name { get; set; }
            public string Size { get; set; }
            public string Extension { get; set; }
            public Guid FullPath { get; set; }

        }


    }
}
